package com.study.xml.utils;

import java.io.FileOutputStream;
import java.io.OutputStream;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

/**
* @Name: DOM4JUtils
* @Description: DOM4J操作工具类
* @Author: 李超	lc_jack@foxmail.com
* @CreateDate: 2017-2-26 下午4:55:40 
* @Version: V1.0
 */
public class DOM4JUtils {
	
	public static Document getDocument(String url) {
		SAXReader reader = new SAXReader() ;
		Document document = null ;
		try {
			document = reader.read(url) ;
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return document ;
	}
	
	public static void writeBackXml(Document document, String url) {
		OutputStream out = null ;
		OutputFormat format = null ;
		XMLWriter writer = null ;
		try {
			out = new FileOutputStream(url) ;
			format = OutputFormat.createPrettyPrint() ;
			format.setEncoding("UTF-8") ;
			writer = new XMLWriter(out, format) ;
			writer.write(document) ;
		} catch (Exception e) {
			e.printStackTrace() ;
		} finally {
			if(out != null) {
				try {
					out.close() ;
				} catch (Exception e) {
					e.printStackTrace() ;
				} finally {
					out = null ;
				}
			}
			if(writer != null) {
				try {
					writer.close() ;
				} catch (Exception e) {
					e.printStackTrace() ;
				} finally {
					writer = null ;
				}
			}
		}
	}
	
}
